<?php


namespace app\admin\controller;


use app\admin\model\ProductPartLogModel;
use app\admin\model\PurchaseModel;
use app\admin\model\PurchaseProductOrderModel;
use app\admin\model\PurchaseProductPartModel;
use app\admin\model\ProductSynthesisLogModel;
use app\admin\model\TombareaRowColModel;
use cmf\controller\AdminBaseController;
use think\Db;
use tree\Tree;

class RockOrderController extends AdminBaseController
{

    public function initialize()
    {
        parent::initialize();

    }
    public function index()
    {
        $model = new PurchaseModel();

        $pact_name = $this->request->param('pact_name','');

        // 查询条件
        $where = array();
        $status_enter = $this->request->param('status_enter','');
        $status_out = $this->request->param('status_out','');

        $status_enter != '' && $where['status_enter'] = $status_enter;
        $status_out != '' && $where['status_out'] = $status_out;

        $this->assign("status_enter", $status_enter);
        $this->assign("status_out", $status_out);

        $results = Db::name('purchase')->alias("p")
            ->field("p.*,u.user_nickname as supplier_name")
            ->join('dj_user u','u.id=p.supplier',"left")
            ->where('pact_name', 'like', '%' . $pact_name . '%')
            ->where($where)->order('p.add_time desc ')->paginate('10');

        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("pact_name", $pact_name);
        $this->assign("page", $page);
        return $this->fetch();
    }
    public function orderinfo()
    {
        if ($this->request->isPost()){
            $parem = $this->request->param();
            if (!isset( $parem['product'])){
                $this->error('请选择产品');
            }
            $pact = $parem['pact'];
            $product = $parem['product'];
            $res = PurchaseModel::add($pact,$product);

            if ($res !==false){
                $this->success('提交成功',url('index'));
            }else{
                $this->error('提交失败');
            }
        }
        $users = Db::name("user")->alias('u')->field('u.id,user_nickname,c.department_name')
            ->join('dj_department c','c.id=u.dept_id')
            ->where(['u.user_type'=>2,'c.dept_type'=>5])
            ->select();
        $this->assign("userlist", $users);

        $result['pact_num'] = PurchaseModel::contractSn();
        $result['add_time'] = date('Y-m-d H:i');
        $this->assign("results", $result);
        $this->assign("page", '');
        return $this->fetch();
    }

    public function checkin(){
        $model = new PurchaseModel();
        if ($this->request->isPost()){
            $parem = $this->request->param();
            $rets  = $model->PartUpdataData($parem);
            if ($rets !==false){
                return $this->success('操作成功',url('index'));
            }else{
                return $this->error($model->getError());
            }
        }
        $modelOrder = new PurchaseProductOrderModel();

        $purchase_id = $this->request->param('purchase_id',0);

        $results = $model->alias("p")
            ->field("p.*,u.user_nickname as add_user_name")
            ->join('dj_user u','u.id=p.add_user')
            ->where(['purchase_id'=>$purchase_id])->find();
        $result_order = $modelOrder->alias('po')->field('po.*,p.pro_name,p.pro_length,p.pro_width,p.pro_height')
            ->leftJoin('dj_product p','po.pro_id = p.id')
            ->where(['po.purchase_id'=>$purchase_id])->select();

        $results['acceptor_user']=cmf_get_admin_name();
        $results['warehousing_user']=cmf_get_admin_name();

        $users = Db::name("user")->alias('u')->field('u.id,user_nickname,c.department_name')
            ->join('dj_department c','c.id=u.dept_id')
            ->where(['u.user_type'=>2,'c.dept_type'=>5])
            ->select();
        $this->assign("userlist", $users);
        $this->assign("result", $results);
        $this->assign("result_order", $result_order);
        $this->assign("page", '');
        return $this->fetch();
    }

    // 匹配出库
    public function outbound()
    {
        if ($this->request->isPost()){
            $purchase_id = $this->request->param('purchase_id');
            $pro_id = $this->request->param('pro_id');
            $mw_id = $this->request->param('mw_id');

            Db::startTrans();
            $status = true;
            $mwid = explode(',',trim($mw_id,','));
            $pro_indfo1 = PurchaseProductOrderModel::where(['purchase_id'=>$purchase_id,'pro_id'=>$pro_id])->find();
            if(count($mwid)>$pro_indfo1['match_usable']){
                $this->error('可使用数量不足，产品数量剩余'.$pro_indfo1['match_usable']);
            }
            try {
                foreach ($mwid as $k => &$value) {
                    $pro_indfo = PurchaseProductOrderModel::where(['purchase_id'=>$purchase_id,'pro_id'=>$pro_id])->find();
                    $purchase_info = PurchaseModel::where(['purchase_id'=>$purchase_id])->find();
                    if ($purchase_info['num'] != ($purchase_info['out_num']+1)){
                        $purchase_updata = [
                            'out_num'=>$purchase_info['out_num']+1,
                            'status_out'=>1
                        ];
                    }else{
                        $purchase_updata = [
                            'out_num'=>$purchase_info['out_num']+1,
                            'status_out'=>2
                        ];
                    }

                    if ($pro_indfo['remaining_num']-1!=0){
                        $order_updata=[
                            'remaining_num'=>$pro_indfo['remaining_num']-1,
                            'match_usable'=>$pro_indfo['match_usable']-1,
                            'status_out'=>1
                        ];
                    }else{
                        $order_updata=[
                            'remaining_num'=>$pro_indfo['remaining_num']-1,
                            'match_usable'=>$pro_indfo['match_usable']-1,
                            'status_out'=>2
                        ];
                    }
                    $res1 = PurchaseProductOrderModel::where(['pro_id'=>$pro_id])->where('status_out','neq',2)->update($order_updata);
                    $res2 = PurchaseModel::where(['purchase_id'=>$pro_id])->where('status_out','neq',2)->update($purchase_updata);
                    if ($res1 !==false && $res2!==false) {
                        $res3 = Db::name('tombarea_row_col')->where(['colID' => ['eq', $value]])->update(['col_status' => 1]);
                        if(!$res3){
                            Db::rollback();
                            $status = false;
                        }
                    }else{
                        Db::rollback();
                        $status = false;
                    }
                }

                if ($status){
                    Db::commit();
                    $this->success('匹配出库成功',url('index'));
                }else{
                    $this->error('匹配失败');
                    Db::rollback();
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error("匹配失败", url('index'));
            }
        }
        $name = $this->request->param("name");
        $pro_id = $this->request->param("pro_id");
        $purchase_id = $this->request->param("purchase_id");
        $menu = new Tree();
        $menu->icon = array('&nbsp;', '&nbsp;', '&nbsp;');
        $menu->nbsp = '';
        if(empty($name)){
            $result =  Db::name("cemetery")->field("id,name,parent_id as pId,type")->where(array('is_delete'=>0))
                ->order(array("list_order" => "ASC"))->select()->toArray();
        }else{
            $result =  Db::name("cemetery")->alias("c")
                ->field("c.id,c.name,c.parent_id as pId,c.type")
                ->join("dj_tombarea t","c.id = t.cemetery_id","left")
                ->join("dj_tombarea_row r","t.id = r.tombarea_id","left")
                ->join("dj_tombarea_row_col rc","r.rowID = rc.rowid","left")
                ->join("dj_archives_deceased d","d.tomb_id = rc.colID","left")
                ->where('c.is_delete',0)
                ->where('rc.num',$name)
                ->whereOr('d.deceased_name',"like","%".$name."%")
                ->order(array("list_order" => "ASC"))
                ->select()->toArray();
        }
        $tom = array();
        foreach($result as $k => $v){
            $tombarea = Db::name("tombarea")->field("id,name,'' as type")
                ->where(array("cemetery_id"=>$v["id"],"status"=>1))->order('list_order asc ')
                ->select()->toArray();
            foreach($tombarea as $i => $t){
                $tombarea[$i]['pId'] = $v["id"];
            }
            $tom = array_merge_recursive ( $tom, $tombarea);
        }
        $result = array_merge_recursive ( $tom, $result);

        $this->assign("categorys", json_encode($result));
        $this->assign("name", $name);
        $this->assign("purchase_id", $purchase_id);
        $this->assign("pro_id", $pro_id);

        return $this->fetch();
    }
    // 墓位信息
    public function tombareacol()
    {
        $id = $this->request->param("id");
        $array_list = TombareaRowColModel::getTombRowColById($id);
        $result['data']=$array_list;
        exit(json_encode($result));
    }
    public function getSup($id){
        // 拼接查询条件hql
        $res=Db::name("cemetery")->where(array('is_delete'=>0,'id'=>$id))
            ->select()->toArray();
        // 得到一级数据
        if($res) {
            if($res[0]["parent_id"] != 0) {
                $result = $this->getSup($res[0]["parent_id"]);
            }else{
                $result = array();
            }
            $imgInfo = array_merge_recursive($res, $result);
        }else{
            $imgInfo = array();
        }
        return $imgInfo;
    }

    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0) {
        if ($array[$id]['parent_id']==0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id']==$id){
            return  $i;
        }else{
            $i++;
            return $this->_get_level($array[$id]['parent_id'],$array,$i);
        }
    }
    // 合成记录
    public function synthetic_record(){
        $parem = $this->request->param();
        $po_id= $parem['po_id'];
        $result =ProductSynthesisLogModel::where(['po_id'=>$po_id])->order('create_time desc')->paginate(10);

        $this->assign('result',$result);
        $this->assign('page',   $result->render());
        return $this->fetch();
    }
    //历史记录
    public function history_record(){
        $parem = $this->request->param();
        $purchase_id= $parem['purchase_id'];
        $part_id= $parem['part_id'];

        $model = new ProductPartLogModel();

        $result = $model->where(['purchase_id'=>$purchase_id,'part_id'=>$part_id])->order('add_time desc')->paginate(10);

        $this->assign('result',$result);
        $this->assign('page',   $result->render());
        return $this->fetch();
    }

    /**
     * @param int $type
     * @param $pro_id
     */
    public function ajaxProduct($type=0,$pro_id=0){
        switch ($type){
            case 0:
                $keyword = $this->request->param('keyword','');
                $result = Db::name("product")->alias('s')
                    ->where(['is_delete' => 1,'pro_status'=>1,'if_create'=>1,'pro_type'=>1])
                    ->where('s.pro_name', 'like', '%' . $keyword . '%')
                    ->paginate(10);
                $this->assign("keyword", $keyword);
                $this->assign("result", $result);
                $this->assign("page", $result->render());
                return $this->fetch('product_list');
                break;
            case 1:
                $purchase_id = $this->request->param('purchase_id');
                $purchaseOrderInfo = PurchaseProductOrderModel::where(['purchase_id'=>$purchase_id,'pro_id'=>$pro_id])->field('total_num')->find();

                $info = PurchaseProductPartModel::where(['purchase_id'=>$purchase_id,'pro_id'=>$pro_id])->find();
                $result_list = Db::name("product_info")->alias('pi')
                    ->field("pi.*,concat(c.cate_name,'-',s.stuff_name) as stuff_name")
                    ->join("dj_stuff s", "s.id = pi.icate", "left")
                    ->join("dj_cate c", "c.id = s.cate_id", "left")
                    ->where(['pi.pro_id' =>$pro_id])->select();
                $result=[];
                $total_num = intval($purchaseOrderInfo['total_num']);

                foreach ($result_list as $key=>&$value){
                    $part_info =  PurchaseProductPartModel::where(['pro_id'=>$pro_id,'pro_part_id'=>$value['id'],'purchase_id'=>$purchase_id])->find();
                    if ($part_info){
//                        $value['arrived_num'] = intval($part_info['check_num']);
                        $value['total_num'] =$part_info['total_num'] ;
                        $value['arrived_num'] =$part_info['arrived_num'] ;
                    }else{
                        $value['arrived_num'] = 0;
                        $value['total_num'] = $value['inumber'] *$total_num; ;
                    }
                    $value['pro_part_id'] = $value['id'];
                    $result[]= $value;
                }

                $result = array("total" => 100, "rows" => $result);
                return json($result);
                //return $this->result($result);
                break;
            case 2:
                $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")->join("dj_cate c", "c.id = s.cate_id", "left")->select();
                $this->assign("cate_type", $cate_type);
                $this->assign("cateJson", json_encode($cate_type));
                // 所有产品库
                $allData = Db::name("product")->field("id,pro_name as name")->select();
                $this->assign("allData", $allData);
                // 附件
                $annex = Db::name("annex")->field("id,annex_name as name")->select();
                $this->assign("annex", $annex);
                $this->assign("annexJson", json_encode($annex));
                $where = array(
                    'id' => $pro_id
                );
                $result = Db::name("product")->where($where)->find();
                $this->assign($result);
                // 详情
                $infowhere = array(
                    'pro_id' => $pro_id,
                    'itype' => 1
                );
                $infoData = Db::name("product_info")->where($infowhere)->select();
                $this->assign('infoData', $infoData);
                // 基础
                $basewhere = array(
                    'pro_id' => $pro_id,
                    'itype' => 2
                );
                $baseData = Db::name("product_info")->where($basewhere)->select();
                $this->assign('baseData', $baseData);
                // 盖板
                $platewhere = array(
                    'pro_id' => $pro_id,
                    'itype' => 3
                );
                $plateData = Db::name("product_info")->where($platewhere)->select();
                $this->assign('plateData', $plateData);
                // 栏杆
                $railwhere = array(
                    'pro_id' => $pro_id,
                    'itype' => 4
                );
                $railData = Db::name("product_info")->where($railwhere)->select();
                $this->assign('railData', $railData);
                // 附件
                $annexwhere = array(
                    'pro_id' => $pro_id,
                );
                $annexData = Db::name("product_annex")->where($annexwhere)->select();
                $this->assign('annexData', $annexData);
                return $this->fetch('product_info');
                break;
            case 3:

                break;
        }
    }
    /**
     * 下拉数据
     */
    public function getALlOption()
    {
        $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")->join("dj_cate c", "c.id = s.cate_id", "left")->select();
        $this->assign("cate_type", $cate_type);
        $this->assign("cateJson", json_encode($cate_type));
        // 所有产品库
        $allData = Db::name("product")->field("id,pro_name as name")->select();
        $this->assign("allData", $allData);
        // 附件
        $annex = Db::name("annex")->field("id,annex_name as name")->select();
        $this->assign("annex", $annex);
        $this->assign("annexJson", json_encode($annex));
    }
}